package com.tanhua.admin.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.db.Admin;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AdminService extends ServiceImpl<AdminMapper, Admin> {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 保存生成的验证码
     * @param uuid
     * @param code
     */
    public void saveCode(String uuid, String code) {
        String key = Constants.CAP_CODE + uuid;
        // 缓存验证码，10分钟后失效
        stringRedisTemplate.opsForValue().set(key,code, Duration.ofMinutes(10));
    }

    /**
     * 登录功能实现
     * @param username
     * @param password
     * @param verificationCode
     * @param uuid
     * @return
     */
    public Map login(String username, String password, String verificationCode, String uuid) {
        log.debug("****username{}**********password{}***********verificationCode{}*****************uuid{}*******",username,password,verificationCode,uuid);
        //1 username password是否为空如果为空直接返回
        if (StringUtils.isEmpty(username) ||StringUtils.isEmpty(password)){
            throw new BusinessException("账号或密码不能为空");
        }
        //2 verificationCode是否为空 为空直接返回
        if (StringUtils.isEmpty(verificationCode)){
            throw new BusinessException("验证码不能为空");
        }
        //3 根据uuid查询redis记录是否存在，如果不存在直接返回
        String key = Constants.CAP_CODE + uuid;
        String redisCode = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(redisCode)){
            throw new BusinessException("验证码已经失效，请重新获取");
        }
        //4 如果redis记录存在，跟 用户输入的验证码进行比较
        if (!redisCode.equals(verificationCode)){
            //5 验证码不一样，直接返回
            throw new BusinessException("验证码错误");
        }
            //6 根据账号和密码查询数据库表看用户是否存在
        String md5Password = DigestUtils.md5Hex(password);
        //方式二：通用service
        Admin admin = query().eq("username", username).eq("password", md5Password).one();

        //7 如果记录不存在，直接返回告知用户名或密码错误
        if (admin==null){
            throw new BusinessException("用户名或密码错误");
        }
        //8 生成token并存入redis
        String toeknStr = JwtUtils.createToken(admin.getId(), admin.getUsername());
        //8.1存入redis
        String tokenKey = "TOKEN_" + toeknStr;
        String adminStr = JSON.toJSONString(admin);
        log.debug("******tokenKey****{}********adminStr*******{}***********",tokenKey,adminStr);
        stringRedisTemplate.opsForValue().set(tokenKey,adminStr);
        //9.验证码从redis删除
        stringRedisTemplate.delete(key);
        Map map = new HashMap();
        map.put("token",toeknStr);
        return map;
    }
}
